package net.luohuasheng.bee.proxy.mybatis.executor.mapper;

import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.executor.keygen.KeyGenerator;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.mapping.StatementType;
import org.apache.ibatis.scripting.xmltags.XMLLanguageDriver;
import org.apache.ibatis.session.Configuration;

/**
 * @author luohuasheng
 */
public class CrudMapper {

    private final MapperBuilderAssistant assistant;
    private final Configuration configuration;
    private static final XMLLanguageDriver LANGUAGE_DRIVER = new XMLLanguageDriver();

    public CrudMapper(MapperBuilderAssistant assistant, Configuration configuration) {
        this.assistant = assistant;
        this.configuration = configuration;
    }

    public SqlSource createSqlSource(String xmlSql) {
        return LANGUAGE_DRIVER.createSqlSource(this.configuration, "<script>\n\t" + xmlSql + "</script>", null);
    }

    public MappedStatement addMappedStatement(String id, SqlSource sqlSource, SqlCommandType sqlCommandType, Class<?> parameterClass, Class<?> resultType, KeyGenerator keyGenerator,
                                              String keyProperty, String keyColumn) {

        return assistant.addMappedStatement(id, sqlSource, StatementType.PREPARED, sqlCommandType, null, null, null, parameterClass, null, resultType, null, false, true, false, keyGenerator, keyProperty, keyColumn, configuration.getDatabaseId(), LANGUAGE_DRIVER, null);
    }
}
